package com.gitee.yannzh.rune.support.crud;


import com.gitee.yannzh.rune.support.crud.annotation.View;
import com.gitee.yannzh.rune.support.crud.annotation.ViewField;
import com.gitee.yannzh.rune.support.crud.model.ViewFieldModel;
import com.gitee.yannzh.rune.support.crud.model.ViewModel;
import org.reflections.Reflections;
import org.springframework.util.ReflectionUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author Yann
 * @date 2025/4/18 13:56
 * @description
 * @since 1.0.0
 */
public class ViewResolver {
    public static final Map<String, ViewModel> VIEW_MAP = new HashMap<>();


    public static synchronized void resolve(String packages) {


        // 创建Reflections实例，扫描指定包及其子包    "com.gitee.yannzh.rune.support.crud.vo"
//        Reflections reflections = new Reflections("your.package.name", new SubTypesScanner(false), new TypeAnnotationsScanner());
        Reflections reflections = new Reflections(packages);
        // 查找带有MyAnnotation注解的类
        Set<Class<?>> annotatedClasses = reflections.getTypesAnnotatedWith(View.class);

        // 打印找到的类
        for (Class<?> clazz : annotatedClasses) {
            ViewModel viewModel = new ViewModel();
            View view = clazz.getAnnotation(View.class);
            viewModel.setTitle(view.title());
            viewModel.setClazz(clazz);
            ReflectionUtils.doWithFields(clazz, field -> {
                String fieldName = field.getName();
                ViewField f = field.getAnnotation(ViewField.class);
                viewModel.getColumns().add(ViewFieldModel.ToModelBean(field.getType(),fieldName, f));
            }, field -> field.isAnnotationPresent(ViewField.class));
            ViewContext.putViewModel(view.name(), viewModel);
        }
    }


}
